<template>
  <div class="page-container">
    <!-- 快捷操作 -->
    <list-quick-navigation ref="listQuickNavigationRef" @change="quickNavigationChange" />
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <!-- 排序 -->
      <template #table-summary>
        <a-select v-model="queryParam.sortField" :style="{ width: '200px' }" :options="SORT_OPTIONS" @change="sortChange" />
      </template>
      <template #sync-order>
        <syncOrderButton />
      </template>
      <template #orderInfo="{ record }">
        <div class="order-info-item">
          <div>自有</div>
          <div>{{ record.orderCode }}</div>
        </div>
        <div class="order-info-item" v-if="record.channelOrderCode">
          <div>渠道</div>
          <div>{{ record.channelOrderCode }}</div>
        </div>
        <!-- 订单标签 -->
        <div class="order-info-item" v-if="record.orderLabelList && record.orderLabelList.length > 0">
          <tag type="primary" v-for="(item, index) in record.orderLabelList" :key="index">{{ item }}</tag>
        </div>
      </template>
      <!-- 承租人信息 -->
      <template #rentMember="{ record }">
        <template v-if="record.memberName || record.memberPhone || record.clientName">
          <div
            v-if="usePermission('svms:order:short-order.edit') && [10, 100, 200, 300, 1000].includes(record.orderStatus)"
            class="link-wrapper"
            @click="editLesseeFn(record)"
          >
            <div class="text-link" v-if="record.memberName">{{ record.memberName }}</div>
            <div class="text-link" v-if="record.memberPhone">{{ record.memberPhone }}</div>
          </div>
          <div v-else class="link-wrapper">
            <div class="text-link no-link" v-if="record.memberName">{{ record.memberName }}</div>
            <div class="text-link no-link" v-if="record.memberPhone">{{ record.memberPhone }}</div>
          </div>
          <div class="text-link no-link" style="margin-top: 4px" v-if="record.clientName">{{ record.clientName }}</div>
        </template>
      </template>
      <!-- 车辆信息 -->
      <template #carInfo="{ record }">
        <div class="link-wrapper">
          <!-- 车牌号显示 -->
          <!-- 待排车、待交车 可以进行排车和改排 -->
          <template
            v-if="
              ([10].includes(record.orderStatus) && usePermission('svms:order:short-order.platooncar') && orderIsMaintenance(record)) ||
              ([100].includes(record.orderStatus) && usePermission('svms:order:short-order.replatooncar') && orderIsMaintenance(record))
            "
          >
            <div class="text-link" @click="platoonCarFn(record)">
              {{ record.orderStatus == 10 ? '未排车' : record.carLicenseNo }}
            </div>
          </template>
          <template v-else>
            <div class="text-link no-link">
              {{ record.orderStatus == 10 ? '未排车' : record.carLicenseNo || '-' }}
            </div>
          </template>
          <!-- 车型名称 -->
          <div class="text-link no-link">{{ record.carModelName || '暂无车型' }}</div>
          <!-- 添加同行调车 -->
          <div v-if="record.orderStatus == 10 && orderIsMaintenance(record)" class="text-link" @click="handleToTransfer(record)">
            添加同行调车
          </div>
        </div>
      </template>
      <!-- ota 车辆信息 -->
      <template #otaCarInfo="{ record }">
        <div class="link-wrapper" v-if="record.channelCarLicenseNo || record.channelModelName">
          <!-- 车牌号显示 -->
          <!-- 待排车、待交车 可以进行排车和改排 -->
          <div class="text-link no-link">
            {{ record.channelCarLicenseNo || '-' }}
          </div>
          <!-- 车型名称 -->
          <div class="text-link no-link">{{ record.channelModelName || '-' }}</div>
        </div>
        <div v-else>-</div>
      </template>
      <!-- 取还车门店 -->
      <template #pickupReturnStore="{ record }">
        <div class="content-item pickup">
          <div class="flex items-start content-item-name">
            <tag type="warn" class="tag-pickup">取</tag>
            <div class="flex-1">{{ record.siteName }}</div>
          </div>
          <div class="content-item-tag">
            <tag type="default" size="large">{{ record.sendServiceFlag ? `上门送车: ${record.address}` : '到店取车' }}</tag>
          </div>
        </div>
        <div class="content-item return">
          <div class="flex items-start content-item-name">
            <tag type="success" class="tag-pickup">还</tag>
            <div class="flex-1">{{ record.returnSiteName }}</div>
          </div>
          <div class="content-item-tag">
            <tag type="default" size="large">{{ record.returnServiceFlag ? `上门取车: ${record.returnAddress}` : '到店还车' }} </tag>
          </div>
        </div>
      </template>
      <!-- ota 取还车门店 -->
      <template #otaPickupReturnStore="{ record }">
        <template v-if="record.orderSource == 2 && (record.channelSiteName || record.channelReturnSiteName)">
          <div class="content-item pickup">
            <div class="flex items-start content-item-name">
              <tag type="warn" class="tag-pickup">取</tag>
              <div class="flex-1">{{ record.channelSiteName || '-' }}</div>
            </div>
            <div class="content-item-tag" v-if="record.channelSiteName">
              <tag type="default" size="large">{{ record.sendServiceFlag ? `上门送车: ${record.channelAddress}` : '到店取车' }} </tag>
            </div>
          </div>
          <div class="content-item return">
            <div class="flex items-start content-item-name">
              <tag type="success" class="tag-pickup">还</tag>
              <div class="flex-1">{{ record.channelReturnSiteName || '-' }}</div>
            </div>
            <div class="content-item-tag" v-if="record.channelReturnSiteName">
              <tag type="default" size="large">{{
                record.returnServiceFlag ? `上门取车: ${record.channelReturnAddress}` : '到店还车'
              }}</tag>
            </div>
          </div>
        </template>
        <template v-else> - </template>
      </template>
      <!-- 租赁周期 -->
      <template #leaseRange="{ record }">
        <div class="content-item pickup">
          <div class="flex items-start content-item-name">
            <tag type="warn" class="lease-range-tag">预取</tag>
            <div class="flex-1" v-if="record.startTime">
              {{ record.startTime }}
            </div>
          </div>
        </div>
        <div class="content-item return">
          <div class="flex items-start content-item-name">
            <tag type="success" class="lease-range-tag">预还</tag>
            <div class="flex-1" v-if="record.endTime">
              {{ record.endTime }}
            </div>
          </div>
        </div>
        <div class="content-item pickup" v-if="record.actualStartTime">
          <div class="flex items-start content-item-name">
            <tag type="warn" class="lease-range-tag">实取</tag>
            <div class="flex-1" v-if="record.actualStartTime">
              {{ record.actualStartTime }}
            </div>
          </div>
        </div>
        <div class="content-item return" v-if="record.actualEndTime">
          <div class="flex items-start content-item-name">
            <tag type="success" class="lease-range-tag">实还</tag>
            <div class="flex-1" v-if="record.actualEndTime">
              {{ record.actualEndTime }}
            </div>
          </div>
        </div>
      </template>
      <!-- 押金 -->
      <template #deposit="{ record }">
        <div class="content-item pickup">
          <div class="flex items-start content-item-name">
            <tag :type="tagTypeComputed(record.carDepositStatusName)">{{ record.carDepositStatusName }}</tag>
            <div class="flex-1">
              <span>租车押金：</span>
              <span>{{ record.carDeposit }}</span>
            </div>
          </div>
        </div>
        <!-- 自定义押金 -->
        <template v-if="record.otherDepositList && record.otherDepositList.length > 0">
          <div class="content-item pickup" v-for="(item, index) in record.otherDepositList" :key="index">
            <div class="flex items-start content-item-name">
              <tag :type="['未收', '未退'].includes(item.depositStatusName) ? 'warn' : 'success'">{{ item.depositStatusName }}</tag>
              <div class="flex-1">
                <span>{{ item.depositTypeName }}：</span>
                <span>{{ item.receivedDepositTotalAmount }}</span>
              </div>
            </div>
          </div>
        </template>
        <div class="content-item return">
          <div class="flex items-start content-item-name">
            <tag :type="['未收', '未退'].includes(record.illegalDepositStatusName) ? 'warn' : 'success'">
              {{ record.illegalDepositStatusName }}
            </tag>
            <div class="flex-1">
              <span>违章押金：</span>
              <span>{{ record.illegalDeposit }}</span>
            </div>
          </div>
        </div>
      </template>
      <!-- 车务专员 -->
      <template #staff="{ record }">
        <div class="content-item pickup">
          <div class="flex items-start content-item-name">
            <tag type="primary">交</tag>
            <template v-if="orderStaffCanClick(record, 'staff') && usePermission('svms:order:short-order.edit')">
              <div class="flex-1 staff-can-click" @click="editOrderStaffFn(record)">
                {{ record.giveStaffName || '未指派' }}
                <template v-if="record.giveStaffName && record.giveStaffStatusName">
                  <span :class="getStatusClassName(record.giveStaffStatus)"> | {{ record.giveStaffStatusName }}</span>
                </template>
              </div>
            </template>
            <template v-else>
              <div class="flex-row flex-1">
                {{ record.giveStaffName || '未指派' }}
                <template v-if="record.giveStaffName && record.giveStaffStatusName">
                  <span :class="getStatusClassName(record.giveStaffStatus)"> | {{ record.giveStaffStatusName }}</span>
                </template>
              </div>
            </template>
          </div>
        </div>
        <div class="content-item return">
          <div class="flex items-start content-item-name">
            <tag type="primary">还</tag>
            <template v-if="orderStaffCanClick(record, 'returnStaff') && usePermission('svms:order:short-order.edit')">
              <div class="flex-1 staff-can-click" @click="editOrderStaffFn(record)">
                {{ record.returnStaffName || '未指派' }}
                <template v-if="record.returnStaffName && record.returnStaffStatusName">
                  <span :class="getStatusClassName(record.returnStaffStatus)"> | {{ record.returnStaffStatusName }}</span>
                </template>
              </div>
            </template>
            <template v-else>
              <div class="flex-1">
                {{ record.returnStaffName || '未指派' }}
                <template v-if="record.returnStaffName && record.returnStaffStatusName">
                  <span :class="getStatusClassName(record.returnStaffStatus)"> | {{ record.returnStaffStatusName }}</span>
                </template>
              </div>
            </template>
          </div>
        </div>
      </template>
      <!-- 关联工单 -->
      <template #workOrderList="{ record }">
        <div class="content-item pickup">
          <template v-if="record.workOrderList?.length > 0">
            <div class="flex items-start content-item-name" v-for="item in record.workOrderList" :key="item.workOrderId">
              <tag type="primary">{{ getWorkOrderName(item) }}</tag>
              <div class="flex-1">
                <div
                  :class="{ 'text-link staff-can-click': usePermission('svms:workOrder:workOrder:order') }"
                  @click="() => onClickWorkOrder(item)"
                >
                  {{ item.workOrderNo }}
                  <template v-if="item.workOrderNo">
                    | <span :class="getWorkStatusClassName(item.workOrderStatus)">{{ item.workOrderStatusName }}</span>
                  </template>
                </div>
              </div>
            </div>
          </template>
          <div v-else> 未关联 </div>
        </div>
      </template>
      <template #contractList="{ record }">
        <contractListShow orderType="shortOrder" :list="record.contractList" />
      </template>
      <!-- 备注 -->
      <template #remark="{ record }">
        <div class="remark-info">
          {{ record.remark || '-' }}
        </div>
        <div class="remark-btn" v-if="record.remark" @click="showRemarkModal(record.id)">查看更多</div>
      </template>
      <!-- 创建时间 -->
      <template #createTime="{ record }">
        <div>{{ record.createTime || '-' }}</div>
        <div>{{ record.createUserName || '-' }}</div>
      </template>
    </table-index>
  </div>
  <!-- 车务专员指派 -->
  <order-staff-modal ref="orderStaffModalRef" @ok="loadData" />
  <!-- 取消订单 -->
  <cancel-order-modal ref="cancelOrderModalRef" @ok="loadData()" />
  <!-- 作废订单 -->
  <invalid-order-modal ref="invalidOrderModalRef" @ok="loadData()" />
  <!-- 修改承租人信息 -->
  <edit-lessee-member-modal ref="editLesseeMemberModalRef" @ok="loadData" />
  <!-- 排车 -->
  <car-selector :title="carSelectorModalTitle" ref="carSelectorRef" @ok="loadData" />
  <!-- 结算 -->
  <order-fee ref="orderFeeRef" @feepageConfirm="loadData" />
  <!-- 导入 -->
  <import-modal ref="imoportRef" action="/sOrder/importExcel" download-import="/短租订单导入模板.xlsx" @ok="loadData(1)" />
  <import-modal
    ref="importModalRef"
    action="/sOrder/importAuditingOrderExcel"
    download-import="/已审核订单导入模板.xlsx"
    @ok="loadData(1)"
  />
  <!-- 创建换车单 -->
  <create-change-car-work-modal v-if="createCarWordVisible" ref="createChangeCarWorkModalRef" @ok="loadData" @close="onClose" />
  <!-- 选择车牌号 -->
  <change-license-modal ref="changeLicenseModalRef" :orderCarInfoList="orderCarInfoList" @ok="changeLicenseOk" />

  <good-evaluate-modal v-model="commentVisible" :order-type="1" @ok="loadData" />
  <!-- 备注列表弹框 -->
  <remark-log-modal ref="remarkModalRef" />
  <!-- 添加备注弹框 -->
  <add-remark-modal ref="addRemarkRef" @ok="loadData" />

  <!-- 自定义标签 -->
  <custom-tag-modal v-model="customTagVisible" :order-type="1" ref="customTagRef" @ok="loadData" />
  <!-- 订单费用导出 -->
  <orderCostModal :title="'订单费用导出'" ref="orderCostRef" :fetch="exportOrderFeeExcel" />
  <!-- 生成电子合同 -->
  <generate-contract-modal ref="generateContractModalRef" />
  <!-- 免押码 -->
  <list-deposit-modal ref="depositModalRef" @ok="loadData" />
  <!-- 发送控车钥匙短信 -->
  <message-modal ref="messageModalRef" />
</template>
<!-- todoList -->
<!-- 1 押金状态判断由文字改为 id 值判断 -->
<!-- 2 车务专员 列表字段 yapi 未确认 -->
<script setup name="ShortOrderList">
  import listQuickNavigation from './components/list-quick-navigation.vue'
  import orderStaffModal from './components/list-modals/order-staff-modal.vue'
  import cancelOrderModal from './components/list-modals/cancel-order-modal.vue'
  import invalidOrderModal from './components/list-modals/invalid-order-modal.vue'
  import editLesseeMemberModal from './components/list-modals/edit-lessee-member-modal.vue'
  import changeLicenseModal from './components/list-modals/change-license-modal.vue'
  import remarkLogModal from './components/list-modals/remark-log-modal.vue'
  import addRemarkModal from './components/list-modals/add-remark-modal.vue'
  import carSelector from '@/views/assets/car/stock/car-selector.vue'
  import syncOrderButton from './components/sync-order-button.vue'
  import orderFee from '@/views/confirmFee/order/index.vue'
  import createChangeCarWorkModal from '@/views/business/workOrder/order/components/create-change-car-work-modal.vue'
  import goodEvaluateModal from '../modals/good-evaluate-modal.vue'
  import customTagModal from '../modals/custom-tag-modal.vue'
  import orderCostModal from '../modals/order-cost-modal/index.vue'
  import contractListShow from '../components/contract-list-show.vue'
  import generateContractModal from '../components/generate-contract-modal.vue'
  import listDepositModal from './components/alipay-deposit/list-deposit-modal.vue'
  import messageModal from '../components/message-modal.vue'

  import { ref, reactive, onMounted, onUnmounted, computed, onActivated, nextTick } from 'vue'
  import { Modal, Message, Notification } from '@arco-design/web-vue'
  import { useTable, useFetchTableDataApi, useTableOperates, useTableButtons } from '@/hooks/table'
  import { useExport } from '@/hooks/list'
  import { usePageDict } from '@/hooks/useDict'
  import {
    getList,
    finishCheck,
    finish,
    // exportExcel,
    orderGoodEvaluate,
    carReplaceList,
    getOperateSubject,
    verifyOrder,
    exportOrderFeeExcel,
    exportBaseExcel,
  } from '@/api/order/sOrder'
  import { useRoute } from 'vue-router'
  import { orderIsMaintenance, orderIsTiexing } from './utils.js'
  import bus from '@/utils/bus'
  import { usePermission } from '@/hooks/usePermission'
  import useNavigate from '@/hooks/useNavigate'
  import { cloneDeep } from 'lodash-es'
  import { SORT_OPTIONS } from './../config.js'
  import useUserStore from '@/store/modules/user'
  import { getCarHousekeepDetail } from '@/api/business/workorder'
  import { findUserInfo } from '@/api/asset/maintenance'
  import { getPermissionsByAppUser } from '@/api/user'
  import { getInterceptRefControl, getReCarKey, getCarControlSms } from '@/api/asset/carTbox'
  // 订单拦截hooks
  import useOrderIntercept from './hooks/useTieXingInterceptor'

  const route = useRoute()
  const routeQuery = route.query
  const { navigateTo, navigateToCreate, registerListHotUpdate } = useNavigate()
  const imoportRef = ref()
  const importModalRef = ref()
  const createChangeCarWorkModalRef = ref() //创建换车单
  const createCarWordVisible = ref(false)
  const adminEmployeeId = ref()
  const customTagRef = ref()
  // 生成电子合同浮框
  const generateContractModalRef = ref('')
  //免押码浮框
  const depositModalRef = ref()

  // 读取商户配置开始
  const userStore = useUserStore()
  userStore.setEpDetail(() => {
    bus.emit('enterpriseConfigChange')
  })
  const dict = usePageDict('shortOrderDict')
  const orderFeeRef = ref()
  // dateTime Attrs
  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }

  const tagTypeComputed = (statusStr) => {
    switch (statusStr) {
      case '应收未收':
        return 'warn'
      case '应收已收':
        return 'success'
      case '应退未退':
        return 'danger'
      case '应退已退':
        return 'primary'
      default:
        return 'default'
    }
  }

  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '订单号', prop: 'orderCodeChannelLike', placeholder: '请输入渠道/自有订单号', type: 'a-input' },
      { label: '承租人信息', prop: 'memberNamePhoneLike', placeholder: '请输入承租人姓名/手机号', type: 'a-input' },
      { label: '车牌号', prop: 'carLicenseNoLike', type: 'a-input' },
      { label: '订单状态', prop: 'orderStatusList', type: 'a-select', options: dict.orderStatusEnum, multiple: true },
      { label: '订单标签', prop: 'orderLabels', type: 'a-select', options: dict.orderLabelEnum, multiple: true },
      { label: '订单来源', prop: 'orderSource', type: 'a-select', options: dict.orderSourceEnum },
      {
        label: '订单渠道',
        prop: 'channelType',
        type: 'sysdict-select',
        attrs: { code: 'short_order_channel_type' },
        addable: false,
      },
      { label: '订单获取方式', prop: 'orderAcquisitionType', type: 'remote-select', attrs: { type: 'order_acquisition' } },
      {
        label: '自定义标签',
        type: 'sysdict-select',
        attrs: { code: 'short_order_custom_label' },
        addable: false,
        prop: 'customLabelList',
        multiple: true,
      },
      { label: '取车门店', prop: 'siteIdList', type: 'remote-select', attrs: { type: 'multiple_site_listBystaff' } },
      { label: '车型', prop: 'carModelId', type: 'remote-select', attrs: { type: 'car_model_tenantList' } },
      { label: '还车门店', prop: 'returnSiteIdList', type: 'remote-select', attrs: { type: 'multiple_site_listBystaff' } },
      {
        label: '预计取车时间',
        prop: 'startTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.startTimeBegin = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '预计还车时间',
        prop: 'endTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.endTimeBegin = value[0]
          queryParam.endTimeEnd = value[1]
        },
      },
      {
        label: '实际取车时间',
        prop: 'actualStartTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.actualStartTimeBegin = value[0]
          queryParam.actualStartTimeEnd = value[1]
        },
      },
      {
        label: '实际还车时间',
        prop: 'actualEndTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.actualEndTimeBegin = value[0]
          queryParam.actualEndTimeEnd = value[1]
        },
      },
      {
        label: '下单时间',
        prop: 'orderCreateTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.orderCreateTimeBegin = value[0]
          queryParam.orderCreateTimeEnd = value[1]
        },
      },
      { label: '是否指派交车人', prop: 'giveStaffIsNull', placeholder: '请输入', type: 'a-select', options: dict.isAssignEnum },
      { label: '交车人', prop: 'giveStaffNameLike', placeholder: '请输入', type: 'a-input', maxlength: 30 },
      { label: '是否指派还车人', prop: 'returnStaffIsNull', placeholder: '请输入', type: 'a-select', options: dict.isAssignEnum },
      { label: '还车人', prop: 'returnStaffNameLike', placeholder: '请输入', type: 'a-input', maxlength: 30 },
      { label: '换车人', prop: 'replaceStaffName', placeholder: '请输入', type: 'a-input', maxlength: 30 },
      { label: '运营主体', prop: 'accountIdList', type: 'a-select', options: siteList, multiple: true },
      {
        label: '创建时间',
        prop: 'createTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.createTimeBegin = value[0]
          queryParam.createTimeEnd = value[1]
        },
      },
      { label: '创建人', prop: 'createUserNameLike', placeholder: '请输入', type: 'a-input', maxlength: 30 },
      { label: '租车押金状态', prop: 'carDepositStatusList', type: 'a-select', options: dict.depositStatusEnum, multiple: true },
      { label: '违章押金状态', prop: 'illegalDepositStatusList', type: 'a-select', options: dict.depositStatusEnum, multiple: true },
    ]
  })

  // 订单状态：待排车、待用车时，可变更交车人和还车人
  // 订单状态：用车中时，可变更还车人
  // 订单状态：已还车、已完成、已取消，不可变更交还车人
  // 选择车务专员后，对应的交车和还车操作中，默认交车人和还车人为当前选中，可变更
  // 换车操作，需要重新选择换车人
  /**
   * 是否开启车管家模式
   * 是：判断是否可以指派交/还车人，指派交/还车人后
   * 判断是否交还车人是否接受
   * 接受：判断订单状态是否可以交/还车
   * @param {any} record
   * @param {any} type
   */
  const isNullOrRejected = (status) => status === 3 || status === null
  const isValidStatus = (status, type) => [10, 100].includes(status) || (type === 'returnStaff' && status === 200)

  /** 列表交还车人是否可以修改 true-可以修改 false-不可以修改 */
  const orderStaffCanClick = (record, type) => {
    const {
      isCarHouseKeepOpen,
      assignGiveCarStaffFlag, // 是否可以修改交车人 1-可以修改 0-不可以修改
      assignReturnCarStaffFlag, // 是否可以修改还车人 1-可以修改 0-不可以修改
      giveStaffStatus,
      returnStaffStatus,
      orderStatus,
      inProgressGiveWorkOrderFlag, // 交车工单是否进行中 1-进行中 0-未进行中
      inProgressReturnWorkOrderFlag, // 还车工单是否进行中 1-进行中 0-未进行中
      orderSource, // 是否为渠道订单
      channelOrderMaintenance,
    } = record

    if (isCarHouseKeepOpen === 1) {
      if (type === 'staff' && assignGiveCarStaffFlag === 1) {
        if (orderSource == 1) {
          return isValidStatus(orderStatus, type) && isNullOrRejected(giveStaffStatus)
        } else {
          if (channelOrderMaintenance === 1 || channelOrderMaintenance === null) {
            return true
          } else {
            return isValidStatus(orderStatus, type) && isNullOrRejected(giveStaffStatus)
          }
        }
      }

      if (type === 'returnStaff' && assignReturnCarStaffFlag === 1) {
        if (orderSource == 1) {
          return isValidStatus(orderStatus, type) && isNullOrRejected(returnStaffStatus)
        } else {
          if (channelOrderMaintenance === 1 || channelOrderMaintenance === null) {
            return true
          } else {
            return isValidStatus(orderStatus, type) && isNullOrRejected(returnStaffStatus)
          }
        }
      }

      return false
    } else {
      if (type === 'staff') {
        if (orderSource == 1) {
          return isValidStatus(orderStatus, type) && assignGiveCarStaffFlag === 1 && inProgressGiveWorkOrderFlag === 0
        } else {
          return assignGiveCarStaffFlag === 1 && inProgressGiveWorkOrderFlag === 0
        }
      }

      if (type === 'returnStaff') {
        if (orderSource == 1) {
          return isValidStatus(orderStatus, type) && assignReturnCarStaffFlag === 1 && inProgressReturnWorkOrderFlag === 0
        } else {
          return assignReturnCarStaffFlag === 1 && inProgressReturnWorkOrderFlag === 0
        }
      }
    }
  }

  // 修改承租人
  const editLesseeMemberModalRef = ref()
  const editLesseeFn = (record) => {
    editLesseeMemberModalRef.value.open(record)
  }
  // 修改车务专员
  const orderStaffModalRef = ref()
  const editOrderStaffFn = (record) => {
    orderStaffModalRef.value.open(record, {
      staff: orderStaffCanClick(record, 'staff'),
      returnStaff: orderStaffCanClick(record, 'returnStaff'),
    })
  }
  // 取消订单
  const cancelOrderModalRef = ref()
  const cancelOrderFn = (record) => {
    cancelOrderModalRef.value.open(record)
  }
  // 作废订单
  const invalidOrderModalRef = ref()
  const invalidOrderFn = (record) => {
    invalidOrderModalRef.value.open(record)
  }

  const defaultQueryParam = {
    // 下单时间
    orderCreateTimeRange: [],
    // 预计取车时间
    startTimeRange: [],
    // 预计还车时间
    endTimeRange: [],
    // 实际取车时间
    actualStartTimeRange: [],
    // 实际还车时间
    actualEndTimeRange: [],
    // 创建时间
    createTimeRange: [],
    // 默认排序字段和排序顺序
    sortField: 'orderCreateTime',
    sortType: 'desc',
  }
  // 定义 queryParam
  const queryParam = reactive({
    ...cloneDeep(defaultQueryParam),
  })

  // 快捷导航点击事件
  const quickNavigationChange = (param) => {
    // 清空
    for (var k in queryParam) {
      queryParam[k] = undefined
    }
    // 更新数据
    let newParam = {
      ...cloneDeep(defaultQueryParam),
      ...param,
    }
    for (var k in newParam) {
      queryParam[k] = newParam[k]
    }
    loadData(1)
  }

  // 排车 & 改排
  const carSelectorRef = ref()
  const carSelectorModalTitle = ref('排车')
  const platoonCarFn = (record) => {
    if ([10, 100].includes(record.orderStatus)) {
      const param = {
        // siteId: record.siteId,
        modelId: record.carModelId,
        dateRange: [record.startTime, record.endTime],
        id: record.carId,
        carSource: record.carSource,
      }
      if (record.orderStatus == 10) {
        carSelectorModalTitle.value = '排车'
      } else {
        carSelectorModalTitle.value = '改排'
      }
      carSelectorRef.value.open(param, {
        ...record,
        modelId: record.carModelId,
        platoonCarId: record.orderStatus == 100 ? record.carId : undefined,
      })
    }
  }

  const commentVisible = ref(false)
  const orderCostRef = ref(null)
  const messageModalRef = ref(null)
  const buttons = computed(() => {
    return [
      // {
      //   label: '订单费用导出',
      //   permission: 'svms:order:short-order.orderCostexport',
      //   method: () => {
      //     orderCostRef.value.open(queryParam)
      //   },
      // },
      {
        label: '导入已审核订单',
        permission: 'svms:order:short-order.importAuditOrder',
        show: () => userStore.enterpriseDetail?.config?.orderLabelEnabledList?.includes(2),
        method: () => {
          importModalRef.value.show()
        },
      },
      {
        label: '订单好评',
        permission: 'svms:order:short-order.comment',
        method: () => {
          commentVisible.value = true
        },
      },
      {
        label: '导入',
        permission: 'svms:order:short-order.import',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        label: '导出',
        permission: 'svms:order:short-order.export',
        // permission: 'svms:order:short-order.newExport',
        method: () => {
          useExport(exportBaseExcel, queryParam)
        },
      },
      // {
      //   label: '导出',
      //   permission: 'svms:order:short-order.export',
      //   method: () => {
      //     useExport(exportExcel, queryParam)
      //   },
      // },
      {
        label: '同步订单',
        permission: 'svms:order:short-order.syncOrder',
        show: userStore.epServiceIncludeShortOrder,
        type: 'slot',
        slotName: 'sync-order',
      },
      {
        type: 'primary',
        icon: 'plus',
        show: userStore.epServiceIncludeShortOrder,
        label: '代客下单',
        permission: 'svms:order:short-order.create',
        method: () => {
          navigateToCreate('/short-order/create', '新增-自驾短租订单')
        },
      },
    ]
  })
  const hasRercordCar = (record, operateStr) => {
    if (record.carId) {
      return true
    } else {
      Message.error(`当前车辆为渠道车辆，请先同平台车辆匹配后再${operateStr}`)
      return false
    }
  }
  // 跳转ota渠道
  const navigateToChannel = (record) => {
    const accountSubject = ''.concat(record.accountSubject).split('，').slice(-1).join('')
    usePermission('svms:business:channel:ota.edit')
      ? navigateTo(`/channel-setting/edit/${record.accountId}?tabKey=4`, `${accountSubject}-编辑渠道`)
      : Message.error('您没有OTA渠道管理的编辑权限')
  }
  const customTagVisible = ref(false)
  const operates = computed(() => {
    // 10 待排车 100 待交车 200 用车中 300 已还车 1000 已完成 -100 已取消
    return [
      {
        label: '排车',
        permission: 'svms:order:short-order.platooncar',
        show: (record) => [10].includes(record.orderStatus) && (orderIsMaintenance(record) || orderIsTiexing(record)),
        method: (record) => {
          platoonCarFn(record)
        },
      },
      {
        label: '交车',
        permission: 'svms:order:short-order.givecar',
        show: (record) =>
          [100].includes(record.orderStatus) &&
          record.autoCancelOperate == 1 &&
          record.isCarHouseKeepOpen === 0 &&
          record.inProgressGiveWorkOrderFlag === 0,
        method: (record) => {
          if (useOrderIntercept(record, 'givecar', () => navigateToChannel(record))) return
          if (hasRercordCar(record, '交车')) {
            navigateTo(`/short-order/giveCar/${record.id}`, `${record.orderCode}-交车`)
          }
        },
      },
      {
        label: '还车',
        permission: 'svms:order:short-order.returncar',
        show: (record) =>
          [200].includes(record.orderStatus) &&
          record.autoCancelOperate == 1 &&
          record.isCarHouseKeepOpen === 0 &&
          record.inProgressReturnWorkOrderFlag === 0,
        method: (record) => {
          if (useOrderIntercept(record, 'returnCar', () => navigateToChannel(record))) return
          if (hasRercordCar(record, '还车')) {
            navigateTo(`/short-order/returnCar/${record.id}`, `${record.orderCode}-还车`)
          }
        },
      },
      {
        label: '完成',
        permission: 'svms:order:short-order.complete',
        show: (record) => [300].includes(record.orderStatus) && (orderIsMaintenance(record) || orderIsTiexing(record)),
        method: (record) => {
          let content = '请确认当前订单是否已完成？'
          let okText = '确认'
          finishCheck({ id: record.id }).then((res) => {
            const { feeFlag } = res.result
            if (feeFlag) {
              content = '当前订单还有未完成费用，请先完成费用收/付款，再进行完成操作'
              okText = '结算'
            }
            Modal.confirm({
              title: '完成订单',
              simple: true,
              content,
              cancelText: '关闭',
              bodyClass: 'text-center',
              okText,
              onBeforeOk: (done) => {
                if (okText == '结算') {
                  navigateTo('/short-order/detail/' + record.id + '?tab=2', `${record.orderCode}-短租详情`)
                  return true
                } else {
                  finish({ id: record.id }).then(() => {
                    Notification.success('完成成功')
                    done()
                    loadData()
                  })
                }
              },
            })
          })
        },
      },
      {
        /**
         * orderStatus 10 待排车 100 待用车 200 用车中 300 已还车 1000 已完成 -100 已取消
         */
        label: '订单详情',
        permission: 'svms:order:short-order.detail',
        method: (record) => {
          let carId = record.carId || ''
          let refCode = record.orderCode || ''
          navigateTo(
            '/short-order/detail/' + record.id + '?tab=1&carId=' + carId + '&refCode=' + refCode + '&orderStatus=' + record.orderStatus,
            `${record.orderCode}-短租详情`
          )
        },
      },
      {
        label: '修改车牌号',
        permission: 'svms:order:short-order.editCarLicenseNo',
        show: (record) =>
          (record.orderStatus == 100 && record.channelOrderMaintenance == 1) || [200, 300, 1000].includes(record.orderStatus),
        method: (record) => {
          editCarLicenseNo(record)
        },
      },
      {
        label: '修改订单',
        permission: 'svms:order:short-order.edit',
        show: (record) => [10, 100, 200, 300, 1000].includes(record.orderStatus),
        method: (record) => {
          navigateTo(`/short-order/edit/${record.id}`, `${record.orderCode}-修改订单`)
        },
      },
      {
        label: '结算\\修改费用',
        span: 2,
        permission: 'svms:order:short-order.confirmfee',
        show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
        method: (record) => {
          navigateTo('/short-order/detail/' + record.id + '?tab=2', `${record.orderCode}-短租详情`)
        },
      },
      {
        label: '添加用户缴费',
        permission: 'svms:order:short-order.addfee',
        show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
        method: (record) => {
          navigateTo(`/short-order/addFees/${record.id}`, `${record.orderCode}-添加用户缴费`)
        },
      },
      {
        label: '添加备注',
        // permission: 'svms:order:short-order.addremark',
        show: (record) => {
          if (record.isCarHouseKeepOpen === 1) {
            return true
          } else {
            return usePermission('svms:order:short-order.addremark')
          }
        },
        method: (record) => {
          addRemarkFn(record)
        },
      },
      {
        label: '订单续租',
        permission: 'svms:order:short-order.relet',
        show: (record) => [200].includes(record.orderStatus),
        method: (record) => {
          if (hasRercordCar(record, '续租')) {
            navigateTo(`/short-order/reletOrder/${record.id}`, `${record.orderCode}-订单续租`)
          }
        },
      },
      {
        label: '订单换车',
        permission: 'svms:order:short-order.changecar',
        show: (record) =>
          [200].includes(record.orderStatus) && record.isCarHouseKeepOpen === 0 && record.inProgressReplaceWorkOrderFlag === 0,
        method: (record) => {
          if (useOrderIntercept(record, 'changecar', () => navigateToChannel(record))) return
          if (hasRercordCar(record, '换车')) {
            navigateTo(`/short-order/changeCar/${record.id}`, `${record.orderCode}-订单换车`)
          }
        },
      },
      {
        label: '新增维修',
        permission: 'svms:order:short-order.addRepair',
        show: (record) => [200, 300, 1000].includes(record.orderStatus),
        method: (record) => {
          if (hasRercordCar(record, '新增维修')) {
            navigateTo(`/car-repair/create/${record.id}?page=shortOrder`, `${record.orderCode}-新增维修`)
          }
        },
      },
      {
        label: '新增违章',
        permission: 'svms:order:short-order.addviolation',
        show: (record) => [200, 300, 1000].includes(record.orderStatus),
        method: (record) => {
          if (hasRercordCar(record, '新增违章')) {
            navigateTo(`/car-violation/create/${record.id}?page=shortOrder`, `${record.orderCode}-新增违章`)
          }
        },
      },
      {
        label: '押金退款',
        permission: 'svms:order:short-order.depositrefuse',
        show: (record) => record.canBackDeposit,
        method: (record) => {
          orderFeeRef.value.show(JSON.stringify(record.depositFeeIdList), record.id)
        },
      },
      {
        label: '取消订单',
        permission: 'svms:order:short-order.cancel',
        show: (record) => [10, 100].includes(record.orderStatus) && orderIsMaintenance(record),
        method: (record) => {
          cancelOrderFn(record)
        },
      },
      {
        label: '订单改排',
        permission: 'svms:order:short-order.replatooncar',
        // 自动维护的铁行订单支持改排
        show: (record) => [100].includes(record.orderStatus) && (orderIsMaintenance(record) || orderIsTiexing(record)),
        method: (record) => {
          if (hasRercordCar(record, '改排')) {
            platoonCarFn(record)
          }
        },
      },
      {
        label: '添加报销单',
        permission: 'svms:order:short-order.addReimbursement',
        show: (record) => record.reimbursementFlag === 1 && adminEmployeeId.value,
        method: (record) => {
          const orderParams = {
            refCostType: 2,
            businessType: record.orderType,
            businessId: record.id,
            businessCode: record.orderCode,
            feeOrgId: record.siteId,
            feeOrgName: record.siteName,
            memberName: record.memberName, //承租人姓名
            memberPhone: record.memberPhone, //承租人电话
          }
          navigateTo(`/operate-cost/create-apply?orderParams=${JSON.stringify(orderParams)}`, `${record.orderCode}-新增报销单`)
        },
      },
      {
        label: '添加付款单',
        permission: 'svms:order:short-order.addExpenditure',
        show: (record) => record.expenditureFlag === 1 && adminEmployeeId.value,
        method: (record) => {
          const orderParams = {
            refCostType: 2,
            businessType: record.orderType,
            businessId: record.id,
            businessCode: record.orderCode,
            feeOrgId: record.siteId,
            feeOrgName: record.siteName,
            memberName: record.memberName, //承租人姓名
            memberPhone: record.memberPhone, //承租人电话
          }
          navigateTo(`/operate-cost/create-pay?orderParams=${JSON.stringify(orderParams)}`, `${record.orderCode}-添加付款单`)
        },
      },
      {
        label: '作废订单',
        permission: 'svms:order:short-order.invalidorder',
        show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
        method: (record) => {
          invalidOrderFn(record)
        },
      },
      {
        label: '新增换车单',
        permission: 'svms:order:short-order.addCarChange',
        show: (record) => record.isCarHouseKeepOpen === 1 && record.changeCarOrderFlag === 1 && record.orderStatus === 200,
        method: (record) => {
          createCarWordVisible.value = true
          nextTick(() => {
            createChangeCarWorkModalRef.value.open({ ...record, returnCarTime: record.endTime, orderType: 1, type: 'order' })
          })
        },
      },
      {
        label: '自定义标签',
        permission: 'svms:order:short-order.customlabel',
        method: (record) => {
          customTagVisible.value = true
          customTagRef.value.open(record)
        },
      },
      {
        label: '合同记录',
        permission: 'svms:order:short-order.contract',
        show: (record) => [10, 100, 200, 300, 1000, -100].includes(record.orderStatus),
        method: (record) => {
          navigateTo(`/short-order/detail/${record.id}?tab=8`, `${record.orderCode}-短租详情`)
        },
      },
      {
        label: '生成电子合同',
        // 权限同订单详情>手动生成电子合同
        permission: 'svms:order:short-order.handContract',
        method: (record) => {
          generateContractModalRef.value.show(record, 'shortOrder')
        },
      },
      {
        label: '免押码',
        permission: 'svms:order:short-order.depositfree',
        show: (record) => record.freeDepositCodeShow == 1,
        method: (record) => {
          depositModalRef.value.show(record)
        },
      },
      {
        label: '核实订单',
        permission: 'svms:order:short-order.verifyOrder',
        show: (record) =>
          record.orderLabelList.includes('待审核') && userStore.enterpriseDetail?.config?.orderLabelEnabledList?.includes(2),
        method: (record) => {
          console.log('record', record)

          Modal.confirm({
            title: '核实订单',
            content: '请确认是否核实当前订单？',
            onBeforeOk: (done) => {
              verifyOrder({ id: record.id })
                .then(() => {
                  done(true)
                  Notification.success('核实成功')
                  loadData()
                })
                .catch((error) => {
                  console.log('error', error)
                  done(false)
                })
            },
          })
        },
      },
      {
        label: '操作记录',
        permission: 'svms:order:short-order.operaterecords',
        method: (record) => {
          navigateTo('/short-order/detail/' + record.id + '?tab=9', `${record.orderCode}-短租详情`)
        },
      },
      {
        label: '订单好评',
        permission: 'svms:order:short-order.comment',
        show: (record) => (record.orderStatus === 300 || record.orderStatus === 1000) && !record.orderLabelList?.includes('已好评'),
        method: (record) => {
          Modal.confirm({
            title: '确认好评?',
            onBeforeOk: (done) => {
              orderGoodEvaluate({ idList: [record.id], isCancel: 0 }).then(() => {
                done()
                Notification.success('好评成功')
                loadData()
              })
            },
          })
        },
      },
      {
        label: '取消好评',
        permission: 'svms:order:short-order.comment',
        show: (record) => record.orderLabelList?.includes('已好评'),
        method: (record) => {
          Modal.confirm({
            title: '确认取消好评?',
            onBeforeOk: (done) => {
              orderGoodEvaluate({ idList: [record.id], isCancel: 1 }).then(() => {
                done()
                Notification.success('取消好评成功')
                loadData()
              })
            },
          })
        },
      },
      // 只有当长/短租订单关联了状态处于“未开始、待控车”的虚拟钥匙控车单时，才展示【发送控车钥匙短信】的按钮
      {
        label: '发送控车钥匙短信',
        permission: 'svms:order:short-order.message',
        show: (record) => record.carControlOrderCount,
        method: (record) => {
          if (record.carControlOrderCount == 1) {
            carControlSmsFn(record)
          } else {
            messageModalRef.value.open(record, 'short')
          }
        },
      },
      // 当订单产生了关联控车单时，出现该按钮
      {
        label: '拦截虚拟车钥匙',
        permission: 'svms:order:short-order.interceptRefControl',
        show: (record) => record.orderLabelList?.includes('虚拟车钥匙'),
        method: (record) => {
          carControlFn(record, 'interceptRefControl')
        },
      },
      // 当订单产生了关联控车单时，出现该按钮
      {
        label: '重新下发车钥匙',
        permission: 'svms:order:short-order.reCarKey',
        show: (record) => record.orderLabelList?.includes('虚拟车钥匙'),
        method: (record) => {
          carControlFn(record, 'ReCarKey')
        },
      },
    ]
  })
  // table 配置
  const table = useTable({
    columns: [
      { title: '订单信息', dataIndex: 'orderInfo', slotName: 'orderInfo', width: 230, fixed: 'left' },
      { title: '下单时间', dataIndex: 'orderCreateTime', width: 170 },
      { title: '订单状态', dataIndex: 'orderStatusName', width: 90 },
      { title: '承租人', dataIndex: 'rentMember', slotName: 'rentMember' },
      { title: '车辆信息', dataIndex: 'carInfo', slotName: 'carInfo' },
      { title: 'OTA车辆信息', dataIndex: 'otaCarInfo', slotName: 'otaCarInfo' },
      { title: '订单来源', dataIndex: 'orderSourceName', width: 90 },
      { title: '取还车门店', dataIndex: 'pickupReturnStore', width: 200, slotName: 'pickupReturnStore' },
      { title: 'OTA取还车门店', dataIndex: 'otaPickupReturnStore', width: 200, slotName: 'otaPickupReturnStore' },
      { title: '租赁周期', dataIndex: 'leaseRange', slotName: 'leaseRange', width: 220 },
      { title: '预计租期', dataIndex: 'rentDays', width: 120 },
      { title: '实际租期', dataIndex: 'rentActiveDays', width: 120 },
      { title: '费用金额', dataIndex: 'totalAmount', unit: '元', width: 120 },
      { title: '待结金额', dataIndex: 'receiveAmount', unit: '元', width: 120 },
      { title: '运营支出', dataIndex: 'operateCost', unit: '元', titleTooltipContent: '为订单产生的运营支出总额' },
      {
        title: '平台佣金',
        dataIndex: 'commissionAmount',
        unit: '元',
        titleTooltipContent: '订单的费用生成流水前：平台佣金=对账金额*抽佣比例。订单的费用生成流水后：平台佣金取流水中订单对应的平台佣金',
      },
      { title: '订单利润', dataIndex: 'orderProfit', unit: '元', titleTooltipContent: '订单利润=费用总额-佣金-运营支出' },
      { title: '押金', dataIndex: 'deposit', unit: '元', slotName: 'deposit', width: 240 },
      // { title: '调车费', dataIndex: 'carSecondedAmount', unit: '元' },
      { title: '交/还车人', width: 200, dataIndex: 'staff', slotName: 'staff' },
      { title: '关联工单', width: 300, dataIndex: 'workOrderList', slotName: 'workOrderList' },
      {
        title: '备注',
        slotName: 'remark',
        titleTooltipContent: '备注中展示订单备注、交车备注、还车备注、续租备注、换车备注，存在多条时点击更多查看所有备注信息',
      },
      { title: '合同编号', width: 220, slotName: 'contractList' },
      { title: '运营主体', dataIndex: 'accountSubject' },
      { title: '创建时间', width: 170, dataIndex: 'createTime', slotName: 'createTime' },
    ],
    tableLoading: false,
    operates: operates.value,
    buttons: buttons.value,
  })

  const onClose = () => {
    createCarWordVisible.value = false
  }

  // 是否为管理员角色
  // v5.9.1.2 2024-08-23修改车牌号改为permission控制
  const isAdminRole = ref(false)
  // 列表接口调用
  const listQuickNavigationRef = ref()
  const loadData = (page, type) => {
    createCarWordVisible.value = false
    const fn = useFetchTableDataApi(table, queryParam, getList)
    fn(page)

    findUserInfo().then((res) => {
      adminEmployeeId.value = res.result.employeeId //空是admin
    })
    getPermissionsByAppUser().then((res) => {
      let roleList = res.result.roleList
      let index = roleList?.findIndex((item) => item.admin)
      isAdminRole.value = index != -1 ? true : false
    })
    // before 刷新顶部快捷筛选数据、list-searcher刷新重置 重置快捷筛选
    if (type == 'reset' || type == 'submit') {
      listQuickNavigationRef.value.reset()
    }
    listQuickNavigationRef.value.getStNum()
    // end
  }

  // router的参数转换为api参数
  const renderData = () => {
    if (routeQuery.id) {
      queryParam.orderStatusList = []
      if (routeQuery.id.indexOf(',') !== -1) {
        let orderNoArr = routeQuery.id.split(',').map((i) => Number(i))
        queryParam.orderStatusList = orderNoArr
      } else {
        queryParam.orderStatusList = [Number(routeQuery.id)]
      }
    } else if (routeQuery.name) {
      if (
        ['今日交车', '今日还车', '明日交车', '明日还车', '逾期未交', '逾期未还', '合同签署中(付费版)', '合同签署中(普通版)'].includes(
          routeQuery.name
        )
      ) {
        listQuickNavigationRef.value.clickActiveByLabel(routeQuery.name)
      } else {
        let obj = {
          车辆冲突: 'carRepeat',
        }
        queryParam.orderLabels = []
        queryParam.orderLabels.push(routeQuery.name)
        listQuickNavigationRef.value.clickActive(obj[routeQuery.name])
      }
    } else if (routeQuery.orderNo) {
      queryParam.orderCodeChannelLike = routeQuery.orderNo
    }
  }

  // 添加同行调车
  const handleToTransfer = (record) => {
    navigateTo(
      `/car-transfer/create?source=order&orderCode=${record.orderCode}&siteId=${record.siteId}&startTime=${record.startTime}&endTime=${record.endTime}`
    )
  }

  const getStatusClassName = (status) => {
    switch (status) {
      case 2:
        return 'success'
      case 1:
        return 'warning'
      case 3:
        return 'danger'
    }
  }

  const getWorkStatusClassName = (status) => {
    switch (status) {
      case 1:
        // 待指派
        return 'warning'
      case 2:
        // 待处理
        return 'warning'
      case 3:
        // 待开始
        return 'warning'
      case 4:
        // 进行中
        return 'going'
      case 5:
        // 已完成
        return 'finish'
      case 6:
        // 已取消
        return 'finish'
    }
  }

  const getWorkOrderName = (record) => {
    switch (record.workOrderType) {
      case 1:
        return '交'
      case 2:
        return '还'
      case 3:
        return '换'
    }
  }

  // 排序修改时间
  const sortChange = (value) => {
    const sortField = SORT_OPTIONS.find((item) => item.value === value)
    queryParam.sortField = value
    queryParam.sortType = sortField.sort
    loadData()
  }

  const onClickWorkOrder = (record) => {
    if (usePermission('svms:workOrder:workOrder:order')) {
      navigateTo(`/business/work-order/order?workOrderCode=${record.workOrderNo}`, '订单工单')
    }
  }

  // 修改车牌号判断订单是否有换车操作弹框
  const changeLicenseModalRef = ref()
  // 换车记录列表
  const orderCarInfoList = ref([])
  const editCarLicenseNo = (record) => {
    carReplaceList({ id: record.id }).then((res) => {
      let result = res.result
      // 是否为换车
      if (result.orderCarInfoList?.length > 1) {
        orderCarInfoList.value = result.orderCarInfoList.map((item) => {
          return {
            ...item,
            label: item.licenseNo,
            value: item.id,
          }
        })
        changeLicenseModalRef.value.open(record)
      } else {
        changeLicenseOk(record)
      }
    })
  }
  // 修改车牌号跳转操作
  const changeLicenseOk = (record) => {
    const param = {
      modelId: record.carModelId,
      dateRange: [record.startTime, record.endTime],
      carSource: record.carSource,
      oldOrderCarId: record.oldOrderCarId,
      isEditLicenseNo: true, // 修改车牌号标识
    }
    carSelectorModalTitle.value = '修改车牌号'
    carSelectorRef.value.open(param, {
      ...record,
      modelId: record.carModelId,
      platoonCarId: record.orderStatus == 100 ? record.carId : undefined,
    })
  }

  // 备注查看更多
  const remarkModalRef = ref()
  const showRemarkModal = (id) => {
    remarkModalRef.value.show(id)
  }
  // 添加备注
  const addRemarkRef = ref()
  const addRemarkFn = (record) => {
    addRemarkRef.value.show(record)
  }

  // 拦截虚拟车钥匙/重新下发车钥匙
  const carControlFn = (record, way) => {
    let fetch = way == 'interceptRefControl' ? getInterceptRefControl : getReCarKey
    fetch({ refType: 1, refCode: record.orderCode }).then(() => {
      Message.success(`操作成功`)
      loadData()
    })
  }
  // 发送控车钥匙短信
  const carControlSmsFn = (record) => {
    let fetch = getCarControlSms
    // 1：从短租短信发送  2：从长租短信发送   为空默认从虚拟钥匙控车单发送
    fetch({ id: record.carControlOrderId, type: 1 }).then((res) => {
      Message.success(res.result)
      loadData()
    })
  }

  onActivated(async () => {
    // TODO 整理逻辑&优化
    await getCarHousekeepDetail().then((res) => {
      const carHouseKeepOpen = localStorage.getItem('carHouseKeepOpen') || 0
      const isCarHouseKeepOpen = res.result.isOpenCarHousekeep

      if (isCarHouseKeepOpen != carHouseKeepOpen) {
        for (var k in queryParam) {
          queryParam[k] = defaultQueryParam[k]
        }
        console.log('isCarHouseKeepOpen', isCarHouseKeepOpen, carHouseKeepOpen, queryParam)
        loadData()
        localStorage.setItem('carHouseKeepOpen', isCarHouseKeepOpen)
      }
    })
  })

  /**
   * 获取运营主体筛选项
   */
  const siteList = ref([])
  const getSiteList = () => {
    getOperateSubject().then((res) => {
      siteList.value = res.result.data.map((item) => {
        return {
          label: `${item.sourceName}-${item.subject}`,
          value: item.id,
        }
      })
    })
  }

  onMounted(() => {
    getSiteList()
    renderData()
    loadData(1)
    // 监听到商户配置更新
    bus.on('enterpriseConfigChange', () => {
      // 更新配置
      table.operates = useTableOperates(operates.value)
      table.buttons = useTableButtons(buttons.value)
    })
    // 注册热更新
    registerListHotUpdate(loadData)
  })
  onUnmounted(() => {
    bus.off('enterpriseConfigChange')
  })
</script>

<style lang="less" scoped>
  .link-wrapper {
    font-size: 14px;

    .text-link {
      color: rgb(var(--primary-6));
      cursor: pointer;

      &.no-link {
        color: #1d2129;
        cursor: inherit;
      }
    }

    .text-link + .text-link {
      margin-top: 6px;
    }
  }

  .order-info-item {
    .custom-tag {
      margin-right: 8px;
      margin-bottom: 10px;
    }
  }

  .order-info-item + .order-info-item {
    margin-top: 10px;
  }

  .content-item {
    .content-item-name {
      margin-bottom: 4px;

      .staff-can-click {
        color: rgb(var(--primary-6));
        cursor: pointer;
      }

      .tag-pickup {
        padding: 0 3px;
        line-height: 18px;
      }

      :deep(.custom-tag) {
        margin-right: 6px;
        position: relative;
        top: 1px;
      }
    }

    .content-item-tag :deep(.custom-tag.default) {
      line-height: 20px;
      padding: 4px 8px;
    }
  }

  .content-item + .content-item {
    margin-top: 10px;
  }

  .lease-range-tag {
    padding: 0 !important;
    width: 30px;
    text-align: center;
  }

  .success {
    color: #00b42a;
  }
  .warning {
    color: #ff7d00;
  }
  .danger {
    color: #f76964;
  }
  .going {
    color: #3491fa;
  }
  .finish {
    color: #86909c;
  }
  .remark-info {
    display: -webkit-box;
    text-overflow: ellipsis;
    overflow: hidden;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  .remark-btn {
    color: #1890ff;
    cursor: pointer;
  }
</style>
